package asm;

import org.objectweb.asm.*;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.MethodNode;

import java.util.List;

import static org.objectweb.asm.Opcodes.ASM5;

public class E_removeContent {
    public void removeContentByCoreAPI() throws Exception {
        ClassReader cr = Tool.getClassReader();
        ClassWriter cw = new ClassWriter(0);

        ClassVisitor cv = new ClassVisitor(ASM5, cw) {

            @Override
            public FieldVisitor visitField(int access, String name, String descriptor, String signature, Object value) {
                if (name.equals("a")) {
                    return null;
                }
                return super.visitField(access, name, descriptor, signature, value);
            }

            @Override
            public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) {
                if (name.equals("test01")) {
                    return null;
                }
                return super.visitMethod(access, name, descriptor, signature, exceptions);
            }
        };
        //cr.accept(cv,ClassReader.SKIP_CODE|ClassReader.SKIP_DEBUG);
        cr.accept(cv, 0);
        byte[] bytesModifield = cw.toByteArray();

        Tool.save(this.getClass(), Application.class, bytesModifield);

    }

    public void removeContentByTreeAPI() throws Exception {
        ClassReader cr = Tool.getClassReader();
        ClassNode cn = new ClassNode();
        cr.accept(cn, ASM5);
        // 删除 a
        List<FieldNode> fields = cn.fields;
        for (int i = 0; i < fields.size(); i++) {
            FieldNode fn = fields.get(i);
            if("a".equals(fn.name)){
                fields.remove(fn);
            }
        }

        // 删除 method
        List<MethodNode> methods = cn.methods;
        for (int i = 0; i < methods.size(); i++) {
            MethodNode mn = methods.get(i);
            if("test01".equals(mn.name)){
                methods.remove(mn);
            }
        }


        // 打印
        ClassWriter cw = new ClassWriter(0);
        cn.accept(cw);
        byte[] bytesModified = cw.toByteArray();
        Tool.save(this.getClass(), Application.class, bytesModified);
    }

    public static void main(String[] args) throws Exception {
        new E_removeContent().removeContentByTreeAPI();
    }
}
